import express from "express";
import { body, param } from "express-validator";
import uploadController from "../controller/upload.controller.js";
import tokenHandler from "../middleware/token.middleware.js";
import validateHandler from "../middleware/validate.middleware.js";

const router = express.Router();
router.use(tokenHandler);

//获取上传配置
router.get(
  "/config",
  uploadController.getUploadSizeLimit
);

//文件上传
router.post(
  "/",
  [
    body("filename").isString().withMessage("filename must be a String"),
    body("size").isInt().withMessage("size must be a Int"),
    body("parentId")
      .optional({ nullable: true })
      .isUUID()
      .withMessage("parentId must be an UUID"),
  ],
  // 表单验证
  validateHandler,
  uploadController.uploadedFile,
);

//文件分片上传
router.post(
  "/file-chunk",
  uploadController.memoryDiskStorage,
  [
    body("hash").isString().withMessage("hash must be a String"),
    body("filename").isString().withMessage("filename must be a String"),
    body("chunkHash").isString().withMessage("chunkHash must be a String"),
  ],
  validateHandler,
  uploadController.uploadChunk,
);

//文件分片上传完成
router.post(
  "/merge",
  [
    body("hash").isString().withMessage("hash must be a String"),
    body("filename").isString().withMessage("filename must be a String"),
    body("size").isInt().withMessage("size must be a Int"),
    body("type").isString().withMessage("type must be a String"),
    body("size").isInt().withMessage("size must be a Int"),
  ],
  validateHandler,
  uploadController.mergeChunks,
);

// 验证文件
router.post(
  "/verify",
  [
    body("hash").isString().withMessage("hash must be a String"),
    body("filename").isString().withMessage("filename must be a String"),
  ],
  validateHandler,
  uploadController.verifyFile,
);

//获取文件封面
router.get(
  "/:hash/cover",
  [
    param("hash").isString().withMessage("fileId must be an String"),
  ],
  validateHandler,
  uploadController.getCover
);
export default router;
